//
//  CollectCityViewController.m
//  BreadTravel
//
//  Created by dllo on 15/12/30.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "CollectCityViewController.h"
#import "CollectCityTableViewCell.h"
#import "WebViewControllerCJT.h"
#import "CoreDataModel.h"
#import "CoreDataManager.h"

@interface CollectCityViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, strong)NSMutableArray *array;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, retain)NSManagedObjectContext *managedObjectContext;

@end

@implementation CollectCityViewController

-(void)viewWillAppear:(BOOL)animated
{
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
}

-(void)getData
{

    _managedObjectContext = [[CoreDataManager shareManager] managedObjectContext];
    //打印沙盒路径
    NSLog(@"沙盒路径~~~~~~ %@", [[CoreDataManager shareManager] applicationDocumentsDirectory]);
    
    //取
    //查询请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //获取要查询的实体的描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
    //对fetchRequest设置查询的实体
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词
    //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"马强"];
    //        [fetchRequest setPredicate:predicate];
    //     Specify how the fetched objects should be sorted
    //排序
    //第一个参数：按哪个字段排序
    //第二个参数：是否升序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"titleName"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //从数据库中搜索满足上述条件的元素
    
    NSArray *fetchedObjects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error : %@", error);
    }
    
    
    self.array = [NSMutableArray arrayWithArray:fetchedObjects];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-49) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 80;
    
    
    //自定义cell Xib注册
    [self.tableView registerNib:[UINib nibWithNibName:@"CollectCityTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];

}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewControllerCJT *webVC = [[WebViewControllerCJT alloc] init];
    WebViewControllerCJT *model = self.array[indexPath.row];
    webVC.titleName = model.titleName;
    webVC.imageName = model.imageName;
    webVC.webURL = model.webURL;
    [self.navigationController pushViewController:webVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"////// %lu", self.array.count);
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    cell.model = self.array[indexPath.row];
    
    return cell;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //取
        //查询请求
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        //获取要查询的实体的描述
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
        //对fetchRequest设置查询的实体
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        //谓词
        //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"马强"];
        //        [fetchRequest setPredicate:predicate];
        //     Specify how the fetched objects should be sorted
        //排序
        //第一个参数：按哪个字段排序
        //第二个参数：是否升序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"titleName"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        //从数据库中搜索满足上述条件的元素
        
        NSArray *fetchedObjects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"error : %@", error);
        }
        
        CoreDataModel *model = fetchedObjects[indexPath.row];
        
//        NSMutableArray *array= [NSMutableArray array];
//        NSMutableArray *arr = [NSMutableArray arrayWithArray:fetchedObjects];
        
        
//            NSInteger index = [array indexOfObject:model];
//            NSLog(@"//////// %lu", index);
        
            [_managedObjectContext deleteObject:model];
            [[CoreDataManager shareManager] saveContext];
        
        
        
        //取
        //查询请求
        NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];
        //获取要查询的实体的描述
        NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
        //对fetchRequest设置查询的实体
        [fetchRequest1 setEntity:entity1];
        // Specify criteria for filtering which objects to fetch
        //谓词
        //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"马强"];
        //        [fetchRequest setPredicate:predicate];
        //     Specify how the fetched objects should be sorted
        //排序
        //第一个参数：按哪个字段排序
        //第二个参数：是否升序
        NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"titleName"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor1, nil]];
        
        NSError *error1 = nil;
        //从数据库中搜索满足上述条件的元素
        
        NSArray *fetchedObjects1 = [_managedObjectContext executeFetchRequest:fetchRequest error:&error1];
        if (fetchedObjects1 == nil) {
            NSLog(@"error : %@", error);
        }

        
        
        self.array = [NSMutableArray arrayWithArray:fetchedObjects1];
        
        NSLog(@"~~ %lu", self.array.count);
        
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            //显示的文字
            hud.labelText = @"取消收藏成功";
            //是否有遮罩
            hud.dimBackground = NO;
            hud.labelFont = [UIFont boldSystemFontOfSize:22];
            hud.backgroundColor = [UIColor clearColor];
            //提示框的样式
            hud.mode = MBProgressHUDModeCustomView;
            [hud show:YES];
            //两秒之后隐藏
            [hud hide:YES afterDelay:2];
        
    
    }
    
    [self.tableView reloadData];

}

#pragma mark--系统编辑按钮触发的方法
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    //设置tableview编辑状态，随按钮状态改变而改变
    [self.tableView setEditing:editing animated:animated];
}



//设置删除按钮文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"确认删除";
}

#pragma mark--移动
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    //交换数组中两个对象的位置
    [self.array exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}

#pragma mark--设置跨区不能移动
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    //如果移动的源section根目标section是同一个区，那么可以移动
    if (sourceIndexPath.section == proposedDestinationIndexPath.section) {
        return proposedDestinationIndexPath;
    }
    return sourceIndexPath;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
